<?php


namespace backend\components;


use Exception;
use yii\base\BaseObject;

class Result extends BaseObject
{
    private $_code = 0;

    private $_message = '';

    private $_data = null;


    public function getCode()
    {
        return $this->_code;
    }


    public function getMessage()
    {
        return $this->_message;
    }

    /**
     * Notes:
     * User: Administrator
     * DateTime: 2021/4/2 11:47
     * @return |null
     */
    public function getData()
    {
        return $this->_data;
    }

    public function setCode($code)
    {
        $this->_code = $code;
    }


    public function setMessage($message)
    {
        $this->_message = $message;
    }


    public function setData($data)
    {
        $this->_data = $data;
    }


    /**
     * Notes: 解析json
     * User: Administrator
     * DateTime: 2021/4/19 8:55
     * @param string $json
     * @return Result
     * @throws Exception
     */
    public static function newInstance($json = '')
    {
        $decode = [];
        if (!empty($json)) {
            if (is_string($json))
            {
                $decode = json_decode($json, true);
                if (empty($decode) || !is_array($decode))
                {
                    throw new Exception('数据格式错误');
                }
            }
        }
        $result = new Result($decode);
        return $result;
    }


    public function isSuccess()
    {
        return $this->_code = 1000;
    }


    public function __toString()
    {
        return json_encode([
           'code'=>$this->getCode(),
            'data'=>$this->getData(),
            'message'=>$this->getMessage()
        ]);
    }
}